<template>
	<view class="chat-list">
		<view class="header">
			<text>消息列表</text>
		</view>

		<view v-if="loading" class="loading">加载中...</view>

		<view v-else-if="sessions.length === 0" class="empty">
			<text>暂无聊天会话</text>
		</view>

		<view v-else class="session-item" v-for="session in sessions" :key="session.id" @click="goToChat(session)">
			<image :src="session.other_user.avatar" class="avatar"></image>
			<view class="info">
				<text class="name">{{ session.other_user.nickname }}</text>
				<text class="last-msg">{{ session.last_message.content }}</text>
			</view>
			<view v-if="session.unread_count > 0" class="unread">
				<text>{{ session.unread_count }}</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			sessions: [],
			loading: true,
			timer: null
		}
	},
	methods: {
		async loadSessions() {
			try {
				this.loading = true;
				const user = uni.getStorageSync('my_info');
				if (!user?.id) {
					uni.navigateTo({ url: '/pagesA/login/login' });
					return;
				}

				const res = await this.$myRuquest({
					url: '/index/dsnv.chat/getSessions',
					method: 'POST',
					data: { user_id: user.id }
				});

				if (res.data.code === 200) {
					this.sessions = res.data.data || [];
				}
			} catch (e) {
				console.error('加载会话失败:', e);
				uni.showToast({ title: '加载失败', icon: 'none' });
			} finally {
				this.loading = false;
			}
		},
		goToChat(session) {
			if (!session?.other_user?.id) {
				uni.showToast({ title: '无法进入聊天', icon: 'none' });
				return;
			}
			clearInterval(this.timer);
			uni.navigateTo({
				url: `/pages/chat/detail?session_id=${session.id}&other_user_id=${session.other_user.id}`
			});
		},
		startPolling() {
			this.timer = setInterval(() => {
				this.loadSessions();
			}, 10000);
		}
	},
	onShow() {
		this.loadSessions();
	},
	onLoad() {
		this.loadSessions();
		// this.startPolling();
	},
	onUnload() {
		clearInterval(this.timer);
	}
}
</script>

<style>
/* 样式保持不变 */
.loading,
.empty {
	padding: 40rpx;
	text-align: center;
	color: #999;
}

.chat-list {
	padding: 20rpx;
}

.header {
	padding: 20rpx;
	font-size: 36rpx;
	font-weight: bold;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 20rpx;
}

.session-item {
	display: flex;
	padding: 20rpx;
	border-bottom: 1rpx solid #f5f5f5;
	position: relative;
}

.avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.name {
	font-size: 32rpx;
	margin-bottom: 10rpx;
}

.last-msg {
	font-size: 28rpx;
	color: #999;
}

.unread {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	background-color: #f00;
	color: #fff;
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
}
</style>